var gameSize : int = 6;
var MyGems : GameObject [] = new GameObject [6];
var MyMaterial : Material [] = new Material [6];
private var arr : int[,];
private var gemArr = new Array();

function Start ()
{
	gemArr = new GameObject[gameSize, gameSize];
	var clone : GameObject;
	
	for(var x = 0; x < gameSize; x++)
	{
		for(var y = 0; y < gameSize; y++)
		{
			var RandomNumber : int = Random.Range (0, gameSize);
			
			clone = Instantiate (MyGems[RandomNumber],new Vector3(x,y,0),MyGems[RandomNumber].transform.rotation);
			MyGems[RandomNumber].renderer.material = MyMaterial[RandomNumber];
			
			gemArr.Push(clone);
		}
	}
}

// Checks for a match 3 per frame
function FixedUpdate()
{
	// CheckHorizontally();
	CheckVertically();
}

function CheckHorizontally()
{
	/*
	var isMatched : boolean = false;
	var numMatchesFound : int;
	var prevGem : GameObject;
	var currGem : GameObject;
	
	// Start from top left to right
	// and go down from there
	for (var y = gameSize -1; y >= 0; y--)
	{
		for (var x = 0; x < gameSize; x++)
		{
			currGem = gemArr[x,y];
			
			if (prevGem && (currGem.renderer.material.color == prevGem.renderer.material.color))
			{
				numMatchesFound++;
			}
			else
			{
				numMatchesFound = 1;
				if (y != 0)
				{
					prevGem = currGem;
				}
				else
				{
					prevGem = null;
				}
			}
			
			if (numMatchesFound >= 3 )
			{
				Debug.Log("3 or more in a row matched horizontally");
				isMatched = true;
			}
		}
	}
	*/
}

// RHT: Work in progress
function CheckVertically()
{
	var isMatched : boolean = false;
	var numMatchesFound : int = 1;
	var prevGem : GameObject;
	var currGem : GameObject;
	var matchedRunes = new Array();
	
	// Start from top left to right
	// and go down from there
	for (var gem : GameObject in gemArr)
	{
		currGem = gem;
		if (!prevGem)
		{
			prevGem = currGem;
			matchedRunes.Push(prevGem);
			continue;
		}
		
		if (currGem.transform.position.x == prevGem.transform.position.x)
		{
			if (currGem.renderer.material.color == prevGem.renderer.material.color)
			{
				matchedRunes.Push(currGem);
				numMatchesFound++;
				Debug.Log("Match");
			}
		}
		else
		{
			prevGem = null;
			numMatchesFound = 1;
			matchedRunes = new Array();
		}
		
		if (numMatchesFound >= 3 )
		{
			Debug.Log("3 or more in a row matched vertically");
			isMatched = true;
		}
		
		if (isMatched)
		{
			for (var i : GameObject in matchedRunes)
			{
				Destroy(i, 5);
			}
			isMatched = false;
		}
	}
}
